package com.oldman.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class CodeUtil {
    public static void sendCode(String phone,String code){
        String apiKey = "72e9017f8029eb18965a835a0a2308bb";
        String apiUrl = "http://v.juhe.cn/sms/send";

        HashMap<String, String> map = new HashMap<>();
        map.put("key", apiKey);
        map.put("mobile", phone);
        map.put("tpl_id", "265125");
        map.put("vars", "");
        map.put("tpl_value", "#code#="+code);
        map.put("ext", "");

        StringBuffer response = null;
        try {
            URL url = new URL(String.format("%s?%s", apiUrl, params(map)));
            BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
            String inputLine;
            response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (IOException e) {
            throw new RuntimeException("网络异常,短信发送失败");
        }
    }

    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }
}